import React from 'react';
import {Dimensions, ScrollView, StyleSheet, View} from 'react-native';
import HttpUtil from '../network/HttpUtil';
import PropTypes from 'prop-types';
import WaterfallListView from './Waterfall/WaterfallListView';

const WIN_WIDTH = Dimensions.get('window').width;

//闪屏页
class WaterfallListPage extends React.PureComponent {

  static propTypes = {
    url: PropTypes.string,
    params: PropTypes.object,
    dataKey: PropTypes.string,
    renderItem: PropTypes.func,
    separatorHeight: PropTypes.number,
    separatorColor: PropTypes.string,
    separator: PropTypes.object,
    mock: PropTypes.bool,
    pageKey: PropTypes.string,
    pageSizeKey: PropTypes.string,
    /**
     * list本身的ListHeaderComponent
     */
    header: PropTypes.func,
    footer: PropTypes.func,
    contentContainerStyle: PropTypes.object,
    stickyHeader: PropTypes.bool,
    /**
     * 当前page的顶部header
     */
    pageHeader: PropTypes.func,
    startPage: PropTypes.number,
    listFromData: PropTypes.func,
    requestMethod: PropTypes.string,
    index: PropTypes.number,
    emptyViewText: PropTypes.string,
    numColumns: PropTypes.number,
    pagination: PropTypes.bool,
    /**
     * 是否显示list
     */
    hideList: PropTypes.func,
    /**
     * 不显示list时的替代view
     */
    listReplacementComponent: PropTypes.func,

    processDataItem: PropTypes.func,
  };

  static defaultProps = {
    startPage: 1,
    pageSizeKey: 'limit',
    params: {},
    numColumns: 1,
    pagination: true,
  };

  constructor(props) {
    super(props);
  }

  refresh = () => {
    this.listView.refresh();
  };

  onFetch = async (page = 1, startFetch, abortFetch) => {
    try {
      let pageLimit = this.props.params[this.props.pageSizeKey] || 10;
      if (this.props.mock) {
        requestAnimationFrame(() => {
          startFetch([1, 2, 3, 4, 5, 6, 7], pageLimit);
        });
      } else {
        const value = this.props.pageKey || 'curpage';
        if (this.props.requestMethod === 'post') {
          const {data} = await HttpUtil.post(this.props.url, {...this.props.params, [value]: page});
          let list = null;
          if (this.props.listFromData) {
            list = this.props.listFromData(data, this.props.index);
          } else {
            list = this.dataForKeyPath(data, this.props.dataKey);
          }

          if (this.props.processDataItem) {
            for (let i = 0; i < list.length; ++i){
              const item = list[i];
              await this.props.processDataItem(item, i);
            }
          }
          console.log('over');
          startFetch(list, pageLimit);
        } else {
          const {data} = await HttpUtil.get(this.props.url, {...this.props.params, [value]: page});
          let list = null;
          if (this.props.listFromData) {
            list = this.props.listFromData(data, this.props.index);
          } else {
            list = this.dataForKeyPath(data, this.props.dataKey);
          }
          if (this.props.processDataItem) {
            for (let i = 0; i < list.length; ++i){
              const item = list[i];
              await this.props.processDataItem(item, i);
            }
          }
          startFetch(list, pageLimit);
        }
      }
    } catch (err) {
      abortFetch(err.message); //manually stop the refresh or pagination if it encounters network error
      console.log(err);
    }
  };

  dataForKeyPath(data, keyPath) {
    if (!keyPath || keyPath.length === 0) {
      return data;
    }
    if (keyPath.indexOf('.') >= 0) {
      const path = keyPath.split('.');
      let temp = data;
      for (let i = 0; i < path.length; ++i) {
        temp = temp[path[i]];
      }
      return temp;
    } else {
      return data[keyPath];
    }
  }

  renderItem = ({item, index, column}) => {
    if (this.props.renderItem) {
      return this.props.renderItem({item, index, list: this, key: this.props.index, column});
    }
    return <View style={{height: 44}}><Text>a</Text></View>;
  };

  render() {
    const viewStyle = {flex: 1, alignItems: 'stretch', backgroundColor: '#efefef', overflow: 'hidden'};
    return (<View
      style={[viewStyle, this.props.style]}
    >
      {this.props.pageHeader && this.props.pageHeader()}
      {this.renderList()}
    </View>)
      ;
  }

  renderList() {
    if (this.props.hideList && this.props.hideList(this.props.index)) {
      if (this.props.header) {
        return <ScrollView style={{flex: 1}} contentContainerStyle={{alignItems: 'stretch'}}>
          {this.props.header && this.props.header()}
          {this.props.listReplacementComponent && this.props.listReplacementComponent(this.props.index, this)}
        </ScrollView>;
      } else {
        return this.props.listReplacementComponent && this.props.listReplacementComponent(this.props.index, this);
      }
    } else {
      return this.renderListPage();
    }
  }

  getData() {
    return this.listView.getRows();
  }

  _getHeightForItem = ({item}) => {
    if (item.itemHeight) {
      console.log('_getHeightForItem:', item.itemHeight);
      return item.itemHeight;
    }
    return 100;
  };

  renderListPage = () => {
    return <WaterfallListView
      {...this.props}
      ref={list => this.listView = list}
      onFetch={this.onFetch}
      renderItem={this.renderItem}
      refreshableMode={'advanced'}
      numColumns={2}
      getHeightForItem={this._getHeightForItem}
      keyExtractor={(item, index) => {
        if (this.props.keyExtractor) {
          return this.props.keyExtractor({item, index});
        } else {
          return `${index}`;
        }
      }}
    />;
  };

}

const styles = StyleSheet.create({});
export default WaterfallListPage;

